package com.rc.evcharger.common.terminal;


import com.rc.evcharger.common.annotation.ByteLength;
import com.rc.evcharger.common.utils.DataUtil;

import java.lang.reflect.Field;
import java.math.BigDecimal;

/**
 * (CMD=C6) 桩充电功率限制回复指令（桩响应）
 */
public class ElecPileLimitPowerResult {
    @ByteLength(length = 1)
    private String result; // 执行结果

    @ByteLength(decimal = 1)
    private BigDecimal outPower; // 桩当前输出功率

    @ByteLength(length = 4)
    private String obligate; // 预留字段;

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public BigDecimal getOutPower() {
        return outPower;
    }

    public void setOutPower(BigDecimal outPower) {
        this.outPower = outPower;
    }

    public String getObligate() {
        return obligate;
    }

    public void setObligate(String obligate) {
        this.obligate = obligate;
    }

    /**
     * 遍历所有字段，按顺序和长度截取数据
     *
     * @param str    数据域
     * @param source 硬件产商
     */
    public ElecPileLimitPowerResult(String str, String source) {
        try {
            Field[] fields = this.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                ByteLength bl = fields[i].getAnnotation(ByteLength.class);
                if (bl == null) {
                    continue;
                }
                int len = bl.length() * 2 + bl.length() - 1;
                String value = str.substring(0, len);
                if (str.length() > len)
                    str = str.substring(len + 1);
                setValue(fields[i], bl, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void setValue(Field field, ByteLength bl, String value) {
        try {
            if (field.getType().equals(BigDecimal.class)) {
                field.set(this, DataUtil.getBDValue(value, bl.decimal(), true));
            } else {
                field.set(this, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return "ElecPileLimitPowerResult{" +
                "result='" + result + '\'' +
                ", outPower='" + outPower + '\'' +
                ", obligate='" + obligate + '\'' +
                '}';
    }
}
